package com.sikao.app.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sikao.app.R;
import com.sikao.app.app.MyApplication;
import com.sikao.app.bean.Bean;
import com.sikao.app.bean.ChangeHeadPhotoSubmitBean;
import com.sikao.app.bean.UploadPicturesBean;
import com.sikao.app.bean.UserInfoBean;
import com.sikao.app.dao.BasicInfModel;
import com.sikao.app.dao.ChangeHeadPhotoModel;
import com.sikao.app.dao.UploadPicturesModel;
import com.sikao.app.fragment.base.BaseFragment;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.AboutUsActivity;
import com.sikao.app.ui.BuyersCenterActivity;
import com.sikao.app.ui.CompanyApplyActivity;
import com.sikao.app.ui.CreditRecordActivity;
import com.sikao.app.ui.FundRecordActivity;
import com.sikao.app.ui.LoginActivity;
import com.sikao.app.ui.MyConcernActivity;
import com.sikao.app.ui.MyEntrustsActivity;
import com.sikao.app.ui.MyMailActivity;
import com.sikao.app.ui.SelectPictureActivity;
import com.sikao.app.ui.SellerCenterActivity;
import com.sikao.app.ui.SettingsActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.FileUtils;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.R.attr.data;

/**
 * 我的
 */
public class Fragment5 extends BaseFragment implements View.OnClickListener {


	private View rootView;

	private TextView titleTv;
	private TextView settingsTv;
	private CircleImageView imgHead;//头像
	private LinearLayout headLinearlayout;
	private LinearLayout linearlayout;
	private TextView nameTv;//名称
	private TextView balanceTv;//账户余额
	private TextView frozenFundTv;//冻结资金
	private TextView creditValueTv;//信誉值
	private RelativeLayout companyApply;//企业认证
	private RelativeLayout fundRecord;//资金记录
	private RelativeLayout creditRecord;//信誉记录
	private RelativeLayout myConcern;//我的关注
	private RelativeLayout myMail;//我的站内信
	private RelativeLayout myEntrust;//我的站内信
	private RelativeLayout buyerCenter;//买家中心
	private RelativeLayout sellerCenter;//卖家中心
	private RelativeLayout aboutusRl;//卖家中心
	private Intent intent;

	public static final int REQUEST_CUT_PHOTO = 20;
	public static final int REQUEST_GET_PHOTO = 21;
	private String picturePath;//图片路径
	private String cuttedPicturePath;//裁剪后的图片路径
	private String uploadPicturePath;//上传后后的图片路径
	private UploadPicturesModel uploadPicturesModel;
	private ChangeHeadPhotoModel changeHeadPhotoModel;
	private ChangeHeadPhotoSubmitBean changeHeadPhotoSubmitBean;
	private BasicInfModel basicInfModel;
	private ImageLoader imageLoader = ImageLoader.getInstance();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		initData();
		rootView = inflater.inflate(R.layout.fragment5, container, false);
		initView(rootView);
		initListener();
		init();
		return rootView;
	}

	private void initData() {
	}

	private void initView(View view) {
		titleTv = (TextView) view.findViewById(R.id.title_middle_tv);
		settingsTv = (TextView) view.findViewById(R.id.title_right_tv);
		imgHead = (CircleImageView) view.findViewById(R.id.img_head);
		headLinearlayout = (LinearLayout) view.findViewById(R.id.head_linearlayout);
		linearlayout = (LinearLayout) view.findViewById(R.id.linearlayout);
		nameTv = (TextView) view.findViewById(R.id.name_tv);
		balanceTv = (TextView) view.findViewById(R.id.balance_tv);
		frozenFundTv = (TextView) view.findViewById(R.id.frozen_fund_tv);
		creditValueTv = (TextView) view.findViewById(R.id.credit_value_tv);
		companyApply = (RelativeLayout) view.findViewById(R.id.company_apply);
		aboutusRl = (RelativeLayout) view.findViewById(R.id.rl_about_us);
		myConcern = (RelativeLayout) view.findViewById(R.id.my_concern);
		fundRecord = (RelativeLayout) view.findViewById(R.id.fund_record);
		creditRecord = (RelativeLayout) view.findViewById(R.id.credit_record);
		myMail = (RelativeLayout) view.findViewById(R.id.my_mail);
		myEntrust = (RelativeLayout) view.findViewById(R.id.my_entrust);
		buyerCenter = (RelativeLayout) view.findViewById(R.id.buyer_center);
		sellerCenter = (RelativeLayout) view.findViewById(R.id.seller_center);
	}

	private void init() {
		titleTv.setText("用户中心");
		settingsTv.setText("设置");
		settingsTv.setVisibility(View.VISIBLE);
	}

	private void initListener() {
		settingsTv.setOnClickListener(this);
		imgHead.setOnClickListener(this);
		nameTv.setOnClickListener(this);
		companyApply.setOnClickListener(this);
		aboutusRl.setOnClickListener(this);
		fundRecord.setOnClickListener(this);
		creditRecord.setOnClickListener(this);
		myConcern.setOnClickListener(this);
		myMail.setOnClickListener(this);
		myEntrust.setOnClickListener(this);
		buyerCenter.setOnClickListener(this);
		sellerCenter.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		balanceTv.setText(ConstantClass.balanceValue + "");
		frozenFundTv.setText(ConstantClass.frozenFund + "");
		creditValueTv.setText(ConstantClass.creditValue + "");
		if (ConstantClass.state == 1) {

				basicInfModel = new BasicInfModel(getActivity(), new OnNetBackListener<UserInfoBean>() {
					@Override
					public void netBack(UserInfoBean data) {
						if (data == null) {
							return;
						}
						if (data.getStatus().equals("1")) {
							if (data.getRes().getCheck_status().equals("2")) {
								ConstantClass.isSeller = true;
							}
							if (data.getRes().getCash() != null) {
								ConstantClass.balanceValue = Float.valueOf(data.getRes().getCash());
							}
							if (data.getRes().getFrozen() != null) {
								ConstantClass.frozenFund = Float.valueOf(data.getRes().getFrozen());
							}
							if (data.getRes().getCredit() != null) {
								ConstantClass.creditValue = Float.valueOf(data.getRes().getCredit());
							}
							balanceTv.setText(ConstantClass.balanceValue + "");
							frozenFundTv.setText(ConstantClass.frozenFund + "");
							creditValueTv.setText(ConstantClass.creditValue + "");

							if (!ConstantClass.imgUrl.equals(data.getRes().getImgsrc())) {
								ConstantClass.imgUrl = data.getRes().getImgsrc();
								imageLoader.loadImage(HttpApi.BANNERUTL + ConstantClass.imgUrl, new ImageLoadingListener() {
									@Override
									public void onLoadingStarted(String imageUri, View view) {
									}

									@Override
									public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
									}

									@Override
									public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
										if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
											headLinearlayout.setBackground(new BitmapDrawable(MyApplication.getInstance().getResources(), loadedImage));
										}
										imgHead.setImageBitmap(loadedImage);
									}

									@Override
									public void onLoadingCancelled(String imageUri, View view) {

									}
								});
							}

						}else{
							//此处应该跳转到登陆界面
							Utils.showToast("长时间未操作，登陆失效，请重新登录！");
							ConstantClass.state = 0;
							HttpApi.sessionId = null;
							ConstantClass.type = 0;
							ConstantClass.imgUrl = null;
							ConstantClass.userName = null;
							ConstantClass.phoneNumber = null;
							ConstantClass.balanceValue = 0;
							ConstantClass.frozenFund = 0;
							ConstantClass.creditValue = 0;
                            String className = null;
							intent.setClass(getActivity(), LoginActivity.class);
							intent.putExtra("activity", className);
							startActivity(intent);
						}


					}
				});

			basicInfModel.request("{}", false);
		}
		if (ConstantClass.state == 0) {
			nameTv.setText("马上登录");
			imgHead.setImageResource(R.mipmap.default_head);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
				linearlayout.setBackground(null);
				headLinearlayout.setBackgroundResource(R.mipmap.personal_center_background);
			}
		} else if (ConstantClass.type == 0) {
			ConstantClass.type = 1;
			nameTv.setText(ConstantClass.userName);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
				linearlayout.setBackgroundColor(getActivity().getResources().getColor (R.color.fragment5_background_gray));
			}
			imageLoader.loadImage(HttpApi.BANNERUTL + ConstantClass.imgUrl, new ImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
				}

				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				}

				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
						headLinearlayout.setBackground(new BitmapDrawable(MyApplication.getInstance().getResources(), loadedImage));
					}
					imgHead.setImageBitmap(loadedImage);
				}

				@Override
				public void onLoadingCancelled(String imageUri, View view) {

				}
			});
		}
		super.onResume();

	}

	@Override
	public void onClick(View v) {
		if (intent == null) {
			intent = new Intent();
		}
		String className = null;
		/*switch (v.getId()) {
			case R.id.fund_record://资金记录
				className = FundRecordActivity.class.getName();
				break;
			case R.id.credit_record://信誉记录
				className = CreditRecordActivity.class.getName();
				break;
			case R.id.my_concern://我的关注
				className = MyConcernActivity.class.getName();
				break;
			case R.id.my_mail://我的站内信
				className = MyMailActivity.class.getName();
				break;
			case R.id.my_entrust://我的委托
				className = MyEntrustsActivity.class.getName();
				break;
			case R.id.buyer_center://买家中心
				className = BuyersCenterActivity.class.getName();
				break;
			case R.id.seller_center://卖家中心
				className = SellerCenterActivity.class.getName();
				break;
			case R.id.company_apply: //企业认证
				className = CompanyApplyActivity.class.getName();
				break;
			default:
				break;
		}*/
		if (ConstantClass.state == 0&&v.getId()!=R.id.rl_about_us) {
			intent.setClass(getActivity(), LoginActivity.class);
			intent.putExtra("activity", className);
			startActivity(intent);
			return;
		}
		switch (v.getId()) {
			case R.id.title_right_tv:
				intent.setClass(getActivity(), SettingsActivity.class);
				break;
			case R.id.img_head:
				intent.setClass(getActivity(), SelectPictureActivity.class);
				startActivityForResult(intent, REQUEST_GET_PHOTO);
				getActivity().overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
				return;
			case R.id.fund_record://资金记录
				intent.setClass(getActivity(), FundRecordActivity.class);
				break;
			case R.id.credit_record://信誉记录
				intent.setClass(getActivity(), CreditRecordActivity.class);
				break;
			case R.id.my_concern://我的关注
				intent.setClass(getActivity(), MyConcernActivity.class);
				break;
			case R.id.my_mail://我的站内信
				intent.setClass(getActivity(), MyMailActivity.class);
				break;
			case R.id.my_entrust://我的委托
				intent.setClass(getActivity(), MyEntrustsActivity.class);
				break;
			case R.id.buyer_center://买家中心
				intent.setClass(getActivity(), BuyersCenterActivity.class);
				break;
			case R.id.seller_center://卖家中心
				if (!ConstantClass.isSeller) {
					intent.setClass(getActivity(), CompanyApplyActivity.class);
					Toast.makeText(getActivity(), "还未通过审核", Toast.LENGTH_SHORT).show();
				} else {
					intent.setClass(getActivity(), SellerCenterActivity.class);
				}
				break;
			case R.id.company_apply: //企业认证
				intent.setClass(getActivity(), CompanyApplyActivity.class);
				break;
			case R.id.rl_about_us: //联系 我们
				intent.setClass(getActivity(), AboutUsActivity.class);
				break;
			default:
				break;
		}
			startActivity(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == getActivity().RESULT_OK) {
			switch (requestCode) {
				case REQUEST_GET_PHOTO:
					picturePath = data.getStringExtra("path");
					cutPicture(picturePath);
					break;
				case REQUEST_CUT_PHOTO:
					if (data != null) {
						if (Build.VERSION.SDK_INT < 23 || new File(cuttedPicturePath).exists() == false) {
							Bundle bundle = data.getExtras();
							if (bundle != null) {
								Bitmap photo = bundle.getParcelable("data");
								//photo.
								if (photo != null) {
									//照片的路径
									cuttedPicturePath = FileUtils.imagePath + "output_image" + System.currentTimeMillis() + ".jpg";
									boolean isSuccess = FileUtils.getInstance().saveFileToPath(photo, cuttedPicturePath);
									if (!isSuccess) {
										return;
									}
								}
							}
						}
						//执行最终操作
						uploadPicture("imgHead.png", cuttedPicturePath);
					}
					break;
				default:
					break;
			}
		}

	}

	/**
	 * 裁剪图片
	 *
	 * @param path
	 */

	private void cutPicture(String path) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);

		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 200);

		if (Build.VERSION.SDK_INT >= 23) {
			File outputImage = new File(FileUtils.imagePath, "output_image" + System.currentTimeMillis() + ".jpg");
			cuttedPicturePath = outputImage.getAbsolutePath();
			if (!outputImage.getParentFile().isDirectory()) {
				outputImage.getParentFile().mkdir();
			}
			intent.putExtra("scale", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputImage));
		} else {
			intent.putExtra("crop", "true");// crop为true是设置在开启的intent中设置显示的view可以剪裁
			intent.putExtra("return-data", true);
		}
		startActivityForResult(intent, REQUEST_CUT_PHOTO);
	}

	private void uploadPicture(String type, String picturePath) {
		if (uploadPicturesModel == null) {
			uploadPicturesModel = new UploadPicturesModel(getActivity(), new OnNetBackListener<UploadPicturesBean>() {
				@Override
				public void netBack(UploadPicturesBean data) {
					if (data == null) {
						Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
						return;
					}

					if (data.getStatus().equals("1")) {
						uploadPicturePath = data.getRes().getArr().get(0).getUrl();
						changeHeadPhoto(uploadPicturePath);
					} else {
						Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		Map<String, String> map = new HashMap<>();
		map.put(type, picturePath);
		uploadPicturesModel.request(map, true);
	}

	private void changeHeadPhoto(String path) {
		if (changeHeadPhotoModel == null) {
			changeHeadPhotoSubmitBean = new ChangeHeadPhotoSubmitBean();
			changeHeadPhotoModel = new ChangeHeadPhotoModel(getActivity(), new OnNetBackListener<Bean>() {
				@Override
				public void netBack(Bean data) {
					if (data == null) {
						return;
					}
					if (data.getStatus().equals("1")) {
						ConstantClass.imgUrl = uploadPicturePath;
						imageLoader.loadImage(HttpApi.BANNERUTL + ConstantClass.imgUrl, new ImageLoadingListener() {
							@Override
							public void onLoadingStarted(String imageUri, View view) {
							}

							@Override
							public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
							}

							@Override
							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
									headLinearlayout.setBackground(new BitmapDrawable(MyApplication.getInstance().getResources(), loadedImage));
								}
								imgHead.setImageBitmap(loadedImage);
							}

							@Override
							public void onLoadingCancelled(String imageUri, View view) {

							}
						});
					} else {
						Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		changeHeadPhotoSubmitBean.setImgsrc(path);
		changeHeadPhotoModel.request(JSONUtil.toJSON(changeHeadPhotoSubmitBean), false);
	}

}
